<template>
	<view class="field-select field-form-item">
		<u-form-item :label="label" :required="required" :prop="prop" :right-icon="disabled ? '' : 'arrow-right'">
			<view @click="showPicker = !disabled" style="width: 100%; height: 37px">
				<view class="ellipsis-text" v-if="selectValue == null || selectValue === ''"
					style="color: rgb(192, 196, 204)">{{ placeholder }}</view>
				<view class="ellipsis-text" v-else>{{ selectValue }}</view>
			</view>
			<SelectPopup :showPickerDlg="showPicker" :value="value" :title="label" :multiple="multiple"
				:dataList="dataList" :props="{
					text: props.label,
					value: props.value
				}" :color="color" @input="onChange" @close="showPicker = false" />
		</u-form-item>
	</view>
</template>

<script>
	import {
		findItemFromList
	} from '@/utils';
	import SelectPopup from './SelectPopup/index.vue';
	import {
		validateWidget
	} from '@/utils/validate.js';

	const DEFAULT_PROPS = {
		label: 'name',
		value: 'id'
	};
	export default {
		name: 'fieldSelect',
		props: {
			value: {
				type: [String, Number, Array]
			},
			label: {
				type: String
			},
			prop: {
				type: String
			},
			placeholder: {
				type: String
			},
			disabled: {
				type: Boolean,
				default: false
			},
			required: {
				type: Boolean,
				default: false
			},
			// 是否多选
			multiple: {
				type: Boolean,
				default: false
			},
			dataList: {
				type: Array,
				default: () => []
			},
			// 选中颜色
			color: {
				type: String
			},
			props: {
				type: Object,
				default: () => {
					return {
						...DEFAULT_PROPS
					}
				}
			}
		},
		components: {
			SelectPopup
		},
		data() {
			return {
				dirty: false,
				showPicker: false,
				errorMessage: ''
			}
		},
		methods: {
			onChange(value, value2) {
                
				this.$emit('input', value, value2);
				this.$emit('change', value, value2);
			},
			setDirty(dirty) {
				this.dirty = dirty;
			},
			getDirty() {
				return this.dirty;
			},
			validateWidget() {
				return new Promise((resolve, reject) => {
					validateWidget(this.rules, this.value).then(res => {
						this.errorMessage = '';
						resolve();
					}).catch(e => {
						this.errorMessage = e;
						resolve(e)
					});
				});
			}
		},
		computed: {
			selectValue() {
				// this.validateWidget();
				console.log(this.value)
				if (this.value == null) return '';
				let temp = this.value;
				if (Array.isArray(this.dataList)) {
					if (this.multiple) {
						temp = Array.isArray(this.value) ? this.value.map(item => {
							let node = findItemFromList(this.dataList, item, this.props.value);
							return node ? node[this.props.label] : null;
						}).filter(item => item != null) : this.value;
					} else {
						let node = findItemFromList(this.dataList, this.value, this.props.value);
						if (node) temp = node[this.props.label];
					}
				}
				return Array.isArray(temp) ? temp.join(' / ') : temp;
			}
		}
	}
</script>